<template>
  <el-dialog
    title="新增部门"
    :visible="isShow"
    width="50%"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 表单 -->
    <el-form
      ref="deptFormRef"
      label-width="100px"
      :model="deptForm"
      :rules="deptFormRules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="deptForm.name"
          style="width: 90%"
          placeholder="请输入1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="deptForm.code"
          style="width: 90%"
          placeholder="请输入1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="deptForm.manager"
          placeholder="请选择活动区域"
          style="width: 90%"
        >
          <el-option
            v-for="obj in managerList"
            :key="obj.id"
            :label="obj.username"
            :value="obj.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="deptForm.introduce"
          type="textarea"
          style="width: 90%"
          placeholder="请输入1-300个字符"
        />
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="paimary" @click="handleAddDept">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { getManagerListAPI, addDeptAPI } from '@/api/departments'
export default {
  name: 'AddDept',
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    deptList: {
      type: Array,
      // 引用类型需要写成函数的格式,返回值才是默认值
      default: () => []
    },
    item: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      // rule: rules下的校验规则
      // value: 当前字段的值
      // callback: 回调函数,不通过传入new error()参数: 否则不传参
      // console.log(rule, value, callback)
      // 用value的值去deptList数组做对比
      // some():检测数组中是否有满足条件的元素: 若有返回true;否则返回false
      const isSame = this.deptList.some(item => item.name === value)
      isSame ? callback(new Error(`[${value}]部门已存在`)) : callback()
      // this.deptList.some()
    }
    // 自定义校验编码函数
    const validateCode = (rule, value, callback) => {
      const isSame = this.deptList.some(item => item.code === value)
      isSame ? callback(new Error(`【${value}】编码已存在`)) : callback()
    }

    return {
      managerList: [],
      deptForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 部门表单校验规则
      deptFormRules: {
        name: [
          {
            required: true,
            message: '部门名称不能为空',
            trigger: ['change', 'blur']
          },
          {
            min: 1,
            max: 50,
            message: '长度在1到50个字符',
            trigger: ['change', 'blur']
          },
          {
            validator: validateName,
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '部门编码不能为空',
            trigger: ['change', 'blur']
          },
          {
            min: 1,
            max: 50,
            message: '长度在1到50个字符',
            trigger: ['change', 'blur']
          },
          {
            validator: validateCode,
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          {
            required: true,
            message: '部门介绍不能为空',
            trigger: ['change', 'blur']
          },
          { min: 1, max: 300, message: '长度在1到300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleAddDept() {
      // console.log('submit!')
      // 整体校验
      this.$refs.deptFormRef.validate(async valid => {
        if (!valid) return
        // 发球新增请求
        await addDeptAPI({
          ...this.deptForm,
          // this.item.manager有值，则添加的不是一级部门，当前部门id就是新增部门的pid
          // 否则添加的就是一级部门，一级就要
          pid: this.item.manager ? this.item.id : ''
        })
        // 关闭弹窗
        this.handleClose()
        // 获取部门列表
        // this.$parent: 获取某个组件的父组件（对象）不推荐使用
        // this.$parent.getDeptList()
        // 推荐使用子传父
        this.$emit('add-dept-success')
      })
    },
    async handleOpen() {
      if (this.managerList.length) return
      // 发请求
      const resp = await getManagerListAPI()
      // console.log(resp)
      this.managerList = resp.data
    },
    handleClose() {
      // 触发自定义事件，通知父组件，关闭弹窗
      // 父组件用了sync修饰符，会自动监听@update：isShow事件
      this.$emit('update:isShow', false)
      this.$refs.deptFormRef.resetFields()
    }
  }
}
</script>

<style scoped>
/* .el-input {
  width: 90%;
 }
 .el-select {
  width: 90%;
 } */
</style>
